package com.example.mall.common.advice;

import com.example.mall.common.exception.BizException;
import com.example.mall.common.model.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Mickey
 * @since 2021/7/8
 */
@RestControllerAdvice
public class GlobalExceptionTranslator {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(BizException.class)
    public Result<?> handleError(BizException e) {
        logger.error("errMessage={}", e.getMessage());
        return Result.ofError(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleError(MethodArgumentNotValidException e) {
        return Result.ofError(e.getBindingResult()
                .getFieldErrors()
                .stream()
                .reduce(new StringBuilder(),
                        (a, b) -> a.append(b.getField())
                                .append(": ")
                                .append(b.getDefaultMessage())
                                .append(", "),
                        (a, b) -> null)
                .toString());
    }

    @ExceptionHandler(Exception.class)
    public Result<?> handleError(Exception e) {
        logger.error("errMessage={}", e.getMessage());
        return Result.ofError(e.getMessage());
    }
}
